package com.cjc.sport.controller.admin;

//import com.cjc.sport.entity.*;

import com.cjc.sport.controller.BaseController;
import com.cjc.sport.entity.EnumValidation;
import com.cjc.sport.entity.NumEnum;
import com.cjc.sport.entity.ReturnJson;
import com.cjc.sport.entity.Shuffling;
import com.cjc.sport.entity.SortObject;
import com.cjc.sport.exception.ServiceException;
import com.cjc.sport.mapper.ShufflingMapper;
import com.cjc.sport.service.ShufflingService;
import com.cjc.sport.util.SportUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.ValidationException;
import java.util.List;

/**
 * 管理轮播图服务层
 *
 * @Author: Bruse Queen
 * @Date: 2018/2/28
 */
@RestController
@CrossOrigin
public class ShufflingController extends BaseController {
    /**
     * 日志配置
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ShufflingController.class);
    /**
     * 装配轮播图对象
     */
    @Autowired
    private ShufflingService shufflingService;
    /**
     * 装配轮播图mapper
     */
    @Autowired
    private ShufflingMapper shufflingMapper;

    /**
     * 定义返回对象名
     */
    private ReturnJson result;

    /**
     * 添加序号校验（2018-3-12）
     */

    /**
     * 检查是否存在序号
     *
     * @param request 请求头
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/checkShufflingAdd", method = RequestMethod.POST)
    public ReturnJson checkShufflingAdd(HttpServletRequest request) {
        try {

            JsonObject jsonObject = getJsonObject(request);

            int shufflingNum = jsonObject.has("shufflingNum")
                    ? jsonObject.get("shufflingNum").getAsInt() : 0;

            List<Shuffling> shufflings = shufflingMapper.selectByShufflingNum(shufflingNum);
            if (shufflings.size() == 0) {
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "可以添加此序号！");
            } else {
                result = new ReturnJson(NumEnum.FAIL.getIndex(), "已有此序号！");
            }
        } catch (Exception e) {
            LOGGER.error("ShufflingController--checkShufflingAdd error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 检查是否存在序号
     *
     * @param request 请求头
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/checkShufflingUpdate", method = RequestMethod.POST)
    public ReturnJson checkShufflingUpdate(HttpServletRequest request) {
        try {

            JsonObject jsonObject = getJsonObject(request);

            int shufflingNum = jsonObject.has("shufflingNum")
                    ? jsonObject.get("shufflingNum").getAsInt() : 0;
            String id = jsonObject.has("id")
                    ? jsonObject.get("id").getAsString() : "0";

            List<Shuffling> shufflings = shufflingMapper.selectByShufflingNum(shufflingNum);
            if (!shufflings.isEmpty() && !id.equals(shufflings.get(0).getId())) {
                result = new ReturnJson(NumEnum.FAIL.getIndex(), "已有此序号！");
            } else {
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "可以添加此序号！");
            }

        } catch (Exception e) {
            LOGGER.error("ShufflingController--checkShufflingUpdate error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 新增轮播图
     *
     * @param shuffling 轮播图对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/addShuffling", method = RequestMethod.POST)
    public ReturnJson addShuffling(@RequestBody @Valid Shuffling shuffling) {
        try {
            // 字段校验
            if (shuffling.getShufflingNum() == null) {
                throw new ValidationException("轮播图序号不能为空!");
            }
            // 数据处理
            Shuffling shufflingTemp = SportUtils.removeSpaceForShuffling(shuffling);
            // 执行新增
            shufflingService.addShuffling(shufflingTemp);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "保存数据成功！");

        } catch (ValidationException v) {
            LOGGER.error("ShufflingController--addShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--addShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--addShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 编辑轮播图
     *
     * @param shuffling 轮播图对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/updateShuffling", method = RequestMethod.POST)
    public ReturnJson updateShuffling(@RequestBody @Valid Shuffling shuffling) {
        try {
            // 字段校验
            if (SportUtils.judgeNull(shuffling.getId().trim())
                    || shuffling.getId().length() > EnumValidation.FOURTY.getNum()) {
                throw new ValidationException("请输入合法的轮播图ID!");
            }
            // 数据处理
            Shuffling shufflingTemp = SportUtils.removeSpaceForShuffling(shuffling);
            // 规整
            shufflingTemp.setId(shuffling.getId().trim());
            // 执行编辑
            shufflingService.updateShuffling(shufflingTemp);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "保存数据成功！");

        } catch (ValidationException v) {
            LOGGER.error("ShufflingController--updateShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--updateShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--updateShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 删除轮播图
     *
     * @param shuffling 轮播图对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/deleteShuffling", method = RequestMethod.POST)
    public ReturnJson deleteShuffling(@RequestBody Shuffling shuffling) {
        try {
            // 字段校验
            if (SportUtils.judgeNull(shuffling.getId().trim())
                    || shuffling.getId().length() > EnumValidation.FOURTY.getNum()) {
                throw new ValidationException("请输入合法的轮播图ID!");
            }
            // 规整
            shuffling.setId(shuffling.getId().trim());
            // 执行删除
            shufflingService.deleteShuffling(shuffling);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "删除数据成功！");

        } catch (ValidationException v) {
            LOGGER.error("ShufflingController--deleteShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--deleteShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--deleteShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 获取所有轮播图
     *
     * @param request 请求头
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/getAllShuffling", method = RequestMethod.POST)
    public ReturnJson getAllShuffling(HttpServletRequest request) {
        try {
            // 获取请求头中jsonObject
            JsonObject jsonObject = getJsonObject(request);
            // 页数
            int pageNo = jsonObject.has("pageNum")
                    ? jsonObject.get("pageNum").getAsInt() : 0;
            // 每页条数
            int pageSize = jsonObject.has("pageSize")
                    ? jsonObject.get("pageSize").getAsInt() : EnumValidation.TWO.getNum();
            // 状态码
            int status = jsonObject.has("status")
                    ? jsonObject.get("status").getAsInt() : 0;

            // 设置返回是否有分页的集合
            if (status == 0) {
                // 设置分页
                PageHelper.startPage(pageNo, pageSize);
                // 执行查询
                List<Shuffling> shufflingTemp = shufflingService.getAllShuffling();
                // 强制转换
                Page<Shuffling> shufflings = (Page<Shuffling>) shufflingTemp;
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功!", shufflings, shufflings.getTotal());
            } else {
                // 不分页的轮播图集合
                List<Shuffling> shufflingNoPage = shufflingService.getAllShuffling();
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功!", shufflingNoPage, shufflingNoPage.size());
            }

        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--getAllShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--getAllShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 批量编辑轮播图停留时间
     *
     * @param shuffling 轮播图对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/updateShufflingTime", method = RequestMethod.POST)
    public ReturnJson updateShufflingTime(@RequestBody Shuffling shuffling) {
        try {
            // 字段校验
            if (shuffling.getKeepTime() == null) {
                throw new ValidationException("请输入停留时间!");
            }
            // 执行编辑
            shufflingService.updateShufflingTime(shuffling);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "保存数据成功！");

        } catch (ValidationException v) {
            LOGGER.error("ShufflingController--updateShufflingTime error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--updateShufflingTime error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--updateShufflingTime error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 轮播图排序
     *
     * @param sortObject 排序的key与value
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/sortShuffling")
    public ReturnJson sortCourse(@RequestBody SortObject sortObject) {
        try {
            // 校验
            if (sortObject.getSort().isEmpty()) {
                throw new ValidationException("请输入合法的排序集合！");
            }
            System.out.println(sortObject);
            // 执行排序
            shufflingService.sortShuffling(sortObject.getSort(), sortObject.getPageNum(), sortObject.getPageSize());
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "排序成功！");

        } catch (ValidationException v) {
            LOGGER.error("ShufflingController--sortShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (ServiceException s) {
            LOGGER.error("ShufflingController--sortShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (Exception e) {
            LOGGER.error("ShufflingController--sortShuffling error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

}
